<template>
  <div class="delivery-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>配送管理</span>
          <el-button type="primary" @click="handleAdd">新建配送任务</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="配送员">
          <el-input v-model="searchForm.deliveryMan" placeholder="请输入配送员姓名" />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待分配" value="pending" />
            <el-option label="待取货" value="assigned" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 配送任务列表 -->
      <el-table :data="deliveries" style="width: 100%">
        <el-table-column prop="order_number" label="订单号" />
        <el-table-column prop="customer_name" label="客户名称" />
        <el-table-column prop="address" label="配送地址" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="delivery_time" label="配送时间" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 分配配送员对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配配送员"
      width="30%"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="配送员">
          <el-select v-model="assignForm.deliveryManId" placeholder="请选择配送员">
            <el-option
              v-for="item in deliveryManList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预计送达">
          <el-date-picker
            v-model="assignForm.expectedTime"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="assignForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新配送状态"
      width="30%"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentDelivery.status)">
            {{ getStatusText(currentDelivery.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="更新为">
          <el-select v-model="statusForm.status" placeholder="请选择新状态">
            <el-option label="待取货" value="assigned" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="statusForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatus">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const deliveries = ref([])

async function fetchDeliveries() {
  try {
    const response = await axios.get('/api/delivery/tasks/')
    deliveries.value = response.data
  } catch (error) {
    console.error('Failed to fetch deliveries:', error)
    ElMessage.error('获取配送列表失败')
  }
}

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  deliveryMan: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 配送员列表
const deliveryManList = ref([
  { id: 1, name: '王师傅' },
  { id: 2, name: '李师傅' },
  { id: 3, name: '张师傅' }
])

// 分配对话框数据
const assignDialogVisible = ref(false)
const assignForm = reactive({
  deliveryManId: '',
  expectedTime: '',
  remark: ''
})

// 状态更新对话框数据
const statusDialogVisible = ref(false)
const statusForm = reactive({
  status: '',
  remark: ''
})
const currentDelivery = ref({})

function getStatusType(status) {
  const statusMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

function getStatusText(status) {
  const statusMap = {
    pending: '待配送',
    in_progress: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索条件：', searchForm)
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.deliveryMan = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 分配配送员
const handleAssign = (row) => {
  assignForm.deliveryManId = ''
  assignForm.expectedTime = ''
  assignForm.remark = ''
  assignDialogVisible.value = true
}

// 提交分配
const submitAssign = () => {
  // TODO: 实现分配逻辑
  ElMessage.success('分配成功')
  assignDialogVisible.value = false
}

// 更新状态
const handleUpdateStatus = (row) => {
  currentDelivery.value = row
  statusForm.status = ''
  statusForm.remark = ''
  statusDialogVisible.value = true
}

// 提交状态更新
const submitStatus = () => {
  // TODO: 实现状态更新逻辑
  ElMessage.success('状态更新成功')
  statusDialogVisible.value = false
}

// 查看详情
const handleDetail = (row) => {
  // TODO: 实现详情查看逻辑
  console.log('查看详情：', row)
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

function handleAdd() {
  // TODO: 实现新建配送任务功能
  ElMessage.info('新建配送任务功能开发中')
}

function handleEdit(row) {
  // TODO: 实现编辑配送任务功能
  ElMessage.info('编辑配送任务功能开发中')
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除这个配送任务吗？', '警告', {
      type: 'warning'
    })
    await axios.delete(`/api/delivery/tasks/${row.id}/`)
    ElMessage.success('删除成功')
    fetchDeliveries()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete delivery:', error)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchDeliveries()
})
</script>

<style scoped>
.delivery-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 